import os
from .path import *
import warnings
warnings.simplefilter('ignore')
import configparser
from sqlalchemy import create_engine


"""""" """""" """""" """""" """""" ""
"        读取配置文件内容         "
"""""" """""" """""" """""" """""" ""
# 处理新闻引擎
config_file = os.path.join(HOME_PATH, "setting.ini")
# 读取数据
cfg = configparser.ConfigParser()
cfg.read(config_file, encoding="utf-8")


def get_db_url(section, encoding='utf8'):
    """
    根据配置文件中的 [] 标示的 section 信息生成 db url
    """
    # 获取 host
    try:
        host = cfg[section]['host']
    except Exception as ex:
        raise Exception(
            "can not find [{0}][host] in config file".format(section))

    # 获取 user
    try:
        user = cfg[section]['user']
    except Exception as ex:
        raise Exception(
            "can not find [{0}][user] in config file".format(section))

    # 获取 password
    try:
        password = cfg[section]['password']
    except Exception as ex:
        raise Exception(
            "can not find [{0}][password] in config file".format(section))

    # 获取 db
    try:
        db = cfg[section]['db']
    except Exception as ex:
        raise Exception(
            "can not find [{0}][db] in config file".format(section))

    url = "mysql+pymysql://{0}:{1}@{2}/{3}?charset={4}".format(
        user, password, host, db, encoding)

    return url

def mssql_engine(user, passwd, host, db, encoding):
    return create_engine(
        "mssql+pymssql://{0}:{1}@{2}/{3}".format(user, passwd, host, db),
        encoding=encoding)

def mysql_engine(user, passwd, host, db, encoding):
    return create_engine("mysql+pymysql://{0}:{1}@{2}/{3}?charset={4}".format(
        user, passwd, host, db, encoding))



base_key = 'hcnews'
news_url = {
    'db_type': cfg[base_key]['db_type'],
    'user': cfg[base_key]['user'],
    'passwd': cfg[base_key]['passwd'],
    'host': cfg[base_key]['host'],
    'db': cfg[base_key]['db'],
    'encoding': cfg[base_key]['encoding']
}

news_engine = mysql_engine(
    user=news_url['user'],
    passwd=news_url['passwd'],
    host=news_url['host'],
    db=news_url['db'],
    encoding=news_url['encoding'])